package sfsoftware.game.actor.item;

import java.util.Random;

import sfsoftware.game.TrevorLegacy;
import sfsoftware.game.actor.attributes.Explodable;
import sfsoftware.game.actor.attributes.Wiffable;
import sfsoftware.util.Actor;
import sfsoftware.util.Clock;
import sfsoftware.util.Sound;
import sfsoftware.util.Updatable;

public class Bomb extends Actor implements Updatable, Wiffable {
	// The maximum number of bombs on the screen at one time
	private static final int MAX_BOMBS = 3;
	private static int bombCount = 0;
	
	protected Clock countdownClock = new Clock(75);
	protected int countdown = 30;
	
	private boolean redHue = false;
	
	public Bomb(int destX, int destY)
	{
		super(destX, destY, "items", 80, 0, 40, 40);
		bombCount++;
		if(bombCount > MAX_BOMBS) {
			remove();
		}
	}
	
	public Bomb(int destX, int destY, String texture, int destWidth, int destHeight) {
		super(destX, destY, texture, destWidth, destHeight);
		bombCount++;
		if(bombCount > MAX_BOMBS) {
			remove();
		}
	}

	public Bomb(int destX, int destY, String texture, int srcX, int srcY, int destWidth, int destHeight) {
		super(destX, destY, texture, srcX, srcY, destWidth, destHeight);
		bombCount++;
		if(bombCount > MAX_BOMBS) {
			remove();
		}
	}
	
	@Override
	public void draw()
	{
		if(redHue)
		{
			super.draw(width, height, this.getSrcX(), this.getSrcY(), width, height, 1, 0.27f, 0, 1);
		}
		else
		{
			super.draw();
		}
	}

	protected void explode()
	{
		// Ka-boom!				
		float green = (new Random()).nextFloat() * 0.27f;
		generateParticles(200, 1, green, 0f);	
			
		Actor[] c = new Actor[Actor.cast.size()];
		Actor.cast.toArray(c);	
		
		for(int i = 0; i < c.length; i++)		
		{
			Actor a = (Actor) c[i];
			if(a instanceof Explodable && distanceToActor(a) <= 120)
			{
				Explodable e = (Explodable) a;
				e.explode(this);
			}			
		}
		
		if(distanceToActor(TrevorLegacy.player) <= 100)
		{
			TrevorLegacy.player.explode(this);
		}
		
		// Remove the bomb
		Sound.playSound("bomb");
		remove();
	}
	
	protected void remove()
	{
		super.remove();
		bombCount--;
	}
	
	@Override
	public void update() {
		if(countdownClock.updateClock())
		{			
			countdown--;
			if(countdown <= 0)
			{							
				explode();
			}
			else if(countdown <= 16)
			{
				redHue = !redHue;
			}
		}
	}

	@Override
	public void wiffaHit() {
		if(getAcceleration() <= 0)
		{		
			// Bounce back!
			xDirection = Math.cos(getAngleFromActor(TrevorLegacy.player)) * -1;
			yDirection = Math.sin(getAngleFromActor(TrevorLegacy.player));			

			// Calculate the bounce back based on size and "weight"
			float a  = 4.25f;
			setAcceleration(a);
		}
	}

}
